package com.hj.tools;

import cn.hutool.core.codec.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author < a href="huajian2018@aliyun.com">hj</ a>
 * @Description  AES 对称加密
 */
@Component
public class CypherUtil {

    @Value("${sysConfig.salt}")
    private String salt;

    /**
     * AES加密
     *
     * @param content 待加密内容
     * @return 返回值
     */
    public String AESEncode(String content) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
            BadPaddingException, IllegalBlockSizeException {
        //ENCRYPT_MODE,加密数据
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
        byte[] byte_content = content.getBytes(StandardCharsets.UTF_8);
        byte[] byte_AES = cipher.doFinal(byte_content);
        return Base64.encode(byte_AES);
    }


    /**
     * 解密
     *
     * @param content 解密的内容
     * @return 明文
     */
    public String AESDecode(String content) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
            BadPaddingException, IllegalBlockSizeException, IOException {

        //DECRYPT_MODE,解密数据
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
        byte[] byte_content = Base64.decode(content);
        byte[] byte_decode = cipher.doFinal(byte_content);
        return new String(byte_decode, StandardCharsets.UTF_8);

    }


    private Cipher getCipher(Integer mode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {

        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(salt.getBytes());
        keyGenerator.init(128, random);
        SecretKey original_key = keyGenerator.generateKey();
        byte[] raw = original_key.getEncoded();
        SecretKey key = new SecretKeySpec(raw, "AES");
        //DES/ECB/PKCS5Padding
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(mode, key);
        return cipher;
    }


}



/*
 * import sun.misc.BASE64Decoder;
 * import sun.misc.BASE64Encoder;
 * byte[] byte_content = new BASE64Decoder().decodeBuffer(content);
 * return new BASE64Encoder().encode(byte_AES);  jdk18才有.
 * */
